package toy.keli.edic.view

import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.substring

/**
 * 支持长按选择的文本组件（无输入框样式）
 * @param text 要显示的文本
 * @param style 文本样式（字体、大小等）
 */
@Composable
fun SelectableText(
    text: String,
    modifier: Modifier = Modifier,
    style: TextStyle = MaterialTheme.typography.bodyLarge,
    onWordClick:(word:String)->Unit
) {
    // 管理文本状态（包含选择范围）
    var textFieldValue =TextFieldValue(text = text)
    var textLayoutResult by remember { mutableStateOf<TextLayoutResult?>(null) }

    // 使用BasicTextField实现选择功能，隐藏输入框样式
    BasicTextField(
        value = textFieldValue,
        onValueChange = {
//            textFieldValue = it
        }, // 可选：允许编辑时开启
        modifier = modifier.pointerInput(Unit){
            detectTapGestures { offset ->
                // 1. 将点击坐标转换为字符索引
                val charIndex = textLayoutResult?.getOffsetForPosition(offset) ?: -1
                // 2. 找到索引所在的单词/词组
                val start = text.lastIndexOf(" ",charIndex)+1
                val end = text.indexOf(" ",charIndex)
                val word = text.substring(start,end)
                onWordClick(word)
            }
        },
        textStyle = style.copy(
            color = style.color.takeIf { it != Color.Unspecified }
                ?: MaterialTheme.colorScheme.onBackground
        ),
        // 隐藏光标和输入框装饰
        singleLine = false, // 支持多行
        decorationBox = { innerTextField ->
            // 仅显示文本内容，无输入框样式
            innerTextField()
        },
        // 启用文本选择
        enabled = true,
        readOnly = true, // 设为true禁止编辑，仅允许选择
        onTextLayout = { textLayoutResult = it }
    )
}